# -*- coding: utf-8 -*-
"""
管理员后台API接口
"""

import json
import logging
from datetime import datetime, timedelta
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.db.models import Count, Sum, Q, Avg
from django.core.paginator import Paginator

from Server.models import User, Store, Takeout, Order, Payment, Message, Discuss, Menu, Address
from Server.enum import (
    CommonSuccessCode, CommonErrorCode, UserBackCode,
    StoreState, TakeoutState, OrderState
)

logger = logging.getLogger(__name__)

# ==================== 权限验证装饰器 ====================

def admin_required(view_func):
    """管理员权限验证装饰器"""
    def wrapper(request, *args, **kwargs):
        try:
            if request.method == 'GET':
                admin_id = request.GET.get('admin_id')
            else:
                data = json.loads(request.body or '{}')
                admin_id = data.get('admin_id')
            
            if not admin_id:
                return JsonResponse({
                    'code': CommonErrorCode.param_not_found.value,
                    'error': '缺少管理员ID'
                })
            
            admin = User.objects.get(id=admin_id, is_admin=True)
            logger.info('[管理员操作] %s 执行: %s' % (admin.username, request.path))
            
            return view_func(request, admin=admin, *args, **kwargs)
            
        except User.DoesNotExist:
            logger.warning('[权限验证失败] ID: %s' % admin_id)
            return JsonResponse({
                'code': UserBackCode.not_admin_user.value,
                'error': '权限不足，非管理员用户'
            })
        except Exception as e:
            logger.error('[管理员验证异常] %s' % str(e))
            return JsonResponse({
                'code': CommonErrorCode.server_error.value,
                'error': '服务器错误'
            })
    return wrapper


# ==================== 系统仪表板 ====================

@csrf_exempt
@admin_required
def admin_dashboard(request, admin=None):
    """
    管理员仪表板 - 系统概况
    GET /api/admin/dashboard?admin_id=xxx
    """
    if request.method != 'GET':
        return JsonResponse({'code': CommonErrorCode.method_error.value, 'error': '请求方式错误'})
    
    try:
        # 今日统计
        today = datetime.now().date()
        today_start = datetime.combine(today, datetime.min.time())
        
        # 基础统计
        total_users = User.objects.count()
        total_stores = Store.objects.count()
        total_takeouts = Takeout.objects.count()
        total_orders = Order.objects.count()
        
        # 待审核数量
        pending_stores = Store.objects.filter(state=StoreState.auditing.value).count()
        pending_takeouts = Takeout.objects.filter(state=TakeoutState.auditing.value).count()
        
        # 今日数据
        today_orders = Order.objects.filter(create_time__gte=today_start).count()
        today_revenue = Order.objects.filter(
            create_time__gte=today_start,
            state=OrderState.finished.value
        ).aggregate(total=Sum('price'))['total'] or 0
        
        # 今日新增用户
        today_new_users = User.objects.filter(id__contains=today.strftime('%Y%m%d')).count()
        
        # 最近订单
        recent_orders = Order.objects.select_related('user', 'store', 'takeout').order_by('-create_time')[:10]
        recent_orders_list = []
        for order in recent_orders:
            recent_orders_list.append({
                'id': order.id,
                'order_id': order.order_id,
                'user_name': order.user.username if order.user else 'N/A',
                'store_name': order.store.store_name if order.store else 'N/A',
                'takeout_name': order.takeout.takeout_name if order.takeout else 'N/A',
                'price': order.price,
                'state': order.state,
                'create_time': order.create_time.strftime('%Y-%m-%d %H:%M:%S')
            })
        
        return JsonResponse({
            'code': CommonSuccessCode.success.value,
            'msg': '获取成功',
            'data': {
                'summary': {
                    'total_users': total_users,
                    'total_stores': total_stores,
                    'total_takeouts': total_takeouts,
                    'total_orders': total_orders
                },
                'pending': {
                    'stores': pending_stores,
                    'takeouts': pending_takeouts
                },
                'today': {
                    'orders': today_orders,
                    'revenue': float(today_revenue),
                    'new_users': today_new_users
                },
                'recent_orders': recent_orders_list
            }
        })
    except Exception as e:
        logger.error('[仪表板] 错误: %s' % str(e))
        return JsonResponse({
            'code': CommonErrorCode.server_error.value,
            'error': '获取失败: %s' % str(e)
        })


# ==================== 用户管理 ====================

@csrf_exempt
@admin_required
def admin_get_users(request, admin=None):
    """
    获取用户列表
    GET /api/admin/users?admin_id=xxx&page=1&size=20&keyword=xxx&is_admin=0
    """
    if request.method != 'GET':
        return JsonResponse({'code': CommonErrorCode.method_error.value, 'error': '请求方式错误'})
    
    try:
        page = int(request.GET.get('page', 1))
        size = int(request.GET.get('size', 20))
        keyword = request.GET.get('keyword', '')
        is_admin_filter = request.GET.get('is_admin', '')
        
        # 构建查询
        query = Q()
        if keyword:
            query &= (Q(username__icontains=keyword) | Q(phone__icontains=keyword) | Q(id__icontains=keyword))
        if is_admin_filter != '':
            query &= Q(is_admin=(is_admin_filter == '1'))
        
        users = User.objects.filter(query).order_by('-id')
        
        # 分页
        paginator = Paginator(users, size)
        page_obj = paginator.get_page(page)
        
        users_list = []
        for user in page_obj:
            users_list.append({
                'id': user.id,
                'username': user.username,
                'phone': user.phone,
                'head_portrait': user.head_portrait.url if user.head_portrait else '',
                'is_admin': user.is_admin,
                'balance': user.money  # 前端使用balance字段名
            })
        
        return JsonResponse({
            'code': CommonSuccessCode.success.value,
            'msg': '获取成功',
            'data': {
                'users': users_list,
                'total': paginator.count,
                'page': page,
                'size': size,
                'total_pages': paginator.num_pages
            }
        })
    except Exception as e:
        logger.error('[用户列表] 错误: %s' % str(e))
        return JsonResponse({
            'code': CommonErrorCode.server_error.value,
            'error': '获取失败: %s' % str(e)
        })


@csrf_exempt
@admin_required
def admin_get_user_detail(request, admin=None):
    """
    获取用户详情
    GET /api/admin/user/detail?admin_id=xxx&user_id=xxx
    """
    if request.method != 'GET':
        return JsonResponse({'code': CommonErrorCode.method_error.value, 'error': '请求方式错误'})
    
    user_id = request.GET.get('user_id')
    if not user_id:
        return JsonResponse({'code': CommonErrorCode.param_not_found.value, 'error': '缺少用户ID'})
    
    try:
        user = User.objects.get(id=user_id)
        
        # 用户基本信息
        user_info = {
            'id': user.id,
            'username': user.username,
            'phone': user.phone,
            'head_portrait': user.head_portrait.url if user.head_portrait else '',
            'is_admin': user.is_admin,
            'money': user.money
        }
        
        # 用户订单统计
        orders = Order.objects.filter(user=user)
        order_stats = {
            'total': orders.count(),
            'total_spent': orders.aggregate(total=Sum('price'))['total'] or 0
        }
        
        # 用户店铺
        try:
            store = Store.objects.get(user=user)
            store_info = {
                'id': store.id,
                'name': store.store_name,
                'state': store.state,
                'takeout_count': store.takeout_count
            }
        except Store.DoesNotExist:
            store_info = None
        
        # 用户地址数量
        address_count = Address.objects.filter(user=user).count()
        
        return JsonResponse({
            'code': CommonSuccessCode.success.value,
            'msg': '获取成功',
            'data': {
                'user': user_info,
                'order_stats': order_stats,
                'store': store_info,
                'address_count': address_count
            }
        })
    except User.DoesNotExist:
        return JsonResponse({'code': UserBackCode.user_not_found.value, 'error': '用户不存在'})
    except Exception as e:
        logger.error('[用户详情] 错误: %s' % str(e))
        return JsonResponse({'code': CommonErrorCode.server_error.value, 'error': str(e)})


@csrf_exempt
@admin_required
def admin_update_user_balance(request, admin=None):
    """
    修改用户余额
    POST /api/admin/user/balance
    参数: {admin_id, user_id, amount, reason}
    """
    if request.method != 'POST':
        return JsonResponse({'code': CommonErrorCode.method_error.value, 'error': '请求方式错误'})
    
    try:
        data = json.loads(request.body)
        user_id = data.get('user_id')
        amount = float(data.get('amount', 0))
        reason = data.get('reason', '管理员调整')
        
        if not user_id:
            return JsonResponse({'code': CommonErrorCode.param_not_found.value, 'error': '缺少用户ID'})
        
        user = User.objects.get(id=user_id)
        old_balance = user.money
        user.money += amount
        user.save()
        
        logger.info('[余额调整] 管理员:%s 用户:%s 调整金额:%s 原因:%s' % (admin.username, user.username, amount, reason))
        
        return JsonResponse({
            'code': CommonSuccessCode.success.value,
            'msg': '余额调整成功',
            'data': {
                'user_id': user_id,
                'old_balance': old_balance,
                'new_balance': user.money,
                'change': amount
            }
        })
    except User.DoesNotExist:
        return JsonResponse({'code': UserBackCode.user_not_found.value, 'error': '用户不存在'})
    except Exception as e:
        logger.error('[余额调整] 错误: %s' % str(e))
        return JsonResponse({'code': CommonErrorCode.server_error.value, 'error': str(e)})


# ==================== 商家管理 ====================

@csrf_exempt
@admin_required
def admin_get_stores(request, admin=None):
    """
    获取商家列表
    GET /api/admin/stores?admin_id=xxx&page=1&size=20&state=xxx&keyword=xxx
    """
    if request.method != 'GET':
        return JsonResponse({'code': CommonErrorCode.method_error.value, 'error': '请求方式错误'})
    
    try:
        page = int(request.GET.get('page', 1))
        size = int(request.GET.get('size', 20))
        keyword = request.GET.get('keyword', '')
        state_filter = request.GET.get('state', '')
        
        # 构建查询
        query = Q()
        if keyword:
            query &= (Q(store_name__icontains=keyword) | Q(id__icontains=keyword))
        if state_filter != '':
            query &= Q(state=int(state_filter))
        
        stores = Store.objects.filter(query).select_related('user').order_by('-create_time')
        
        # 分页
        paginator = Paginator(stores, size)
        page_obj = paginator.get_page(page)
        
        stores_list = []
        for store in page_obj:
            stores_list.append({
                'id': store.id,
                'store_name': store.store_name,
                'address': store.address,
                'takeout_count': store.takeout_count,
                'state': store.state,
                'state_name': get_store_state_name(store.state),
                'introduce': store.introduce,
                'owner': {
                    'id': store.user.id if store.user else '',
                    'username': store.user.username if store.user else 'N/A',
                    'phone': store.user.phone if store.user else 'N/A'
                },
                'create_time': store.create_time.strftime('%Y-%m-%d %H:%M:%S')
            })
        
        return JsonResponse({
            'code': CommonSuccessCode.success.value,
            'msg': '获取成功',
            'data': {
                'stores': stores_list,
                'total': paginator.count,
                'page': page,
                'size': size,
                'total_pages': paginator.num_pages
            }
        })
    except Exception as e:
        logger.error('[商家列表] 错误: %s' % str(e))
        return JsonResponse({'code': CommonErrorCode.server_error.value, 'error': str(e)})


@csrf_exempt
@admin_required
def admin_get_pending_stores(request, admin=None):
    """
    获取待审核商家列表
    GET /api/admin/stores/pending?admin_id=xxx
    """
    if request.method != 'GET':
        return JsonResponse({'code': CommonErrorCode.method_error.value, 'error': '请求方式错误'})
    
    try:
        stores = Store.objects.filter(state=StoreState.auditing.value).select_related('user').order_by('create_time')
        
        stores_list = []
        for store in stores:
            stores_list.append({
                'id': store.id,
                'store_name': store.store_name,
                'address': store.address,
                'introduce': store.introduce,
                'owner': {
                    'id': store.user.id if store.user else '',
                    'username': store.user.username if store.user else 'N/A',
                    'phone': store.user.phone if store.user else 'N/A'
                },
                'create_time': store.create_time.strftime('%Y-%m-%d %H:%M:%S')
            })
        
        return JsonResponse({
            'code': CommonSuccessCode.success.value,
            'msg': '获取成功',
            'data': {
                'stores': stores_list,
                'total': len(stores_list)
            }
        })
    except Exception as e:
        logger.error('[待审核商家] 错误: %s' % str(e))
        return JsonResponse({'code': CommonErrorCode.server_error.value, 'error': str(e)})


# ==================== 外卖管理 ====================

@csrf_exempt
@admin_required
def admin_get_takeouts(request, admin=None):
    """
    获取外卖列表
    GET /api/admin/takeouts?admin_id=xxx&page=1&size=20&state=xxx&keyword=xxx
    """
    if request.method != 'GET':
        return JsonResponse({'code': CommonErrorCode.method_error.value, 'error': '请求方式错误'})
    
    try:
        page = int(request.GET.get('page', 1))
        size = int(request.GET.get('size', 20))
        keyword = request.GET.get('keyword', '')
        state_filter = request.GET.get('state', '')
        
        # 构建查询
        query = Q()
        if keyword:
            query &= Q(takeout_name__icontains=keyword)
        if state_filter != '':
            query &= Q(state=int(state_filter))
        
        takeouts = Takeout.objects.filter(query).select_related('store').order_by('-create_time')
        
        # 分页
        paginator = Paginator(takeouts, size)
        page_obj = paginator.get_page(page)
        
        takeouts_list = []
        for takeout in page_obj:
            takeouts_list.append({
                'id': takeout.id,
                'takeout_name': takeout.takeout_name,
                'introduce': takeout.introduce,
                'price': takeout.price,
                'state': takeout.state,
                'state_name': get_takeout_state_name(takeout.state),
                'flow': takeout.flow,
                'mark': takeout.mark,
                'remark_count': takeout.remark_count,
                'store': {
                    'id': takeout.store.id if takeout.store else '',
                    'name': takeout.store.store_name if takeout.store else 'N/A'
                },
                'create_time': takeout.create_time.strftime('%Y-%m-%d %H:%M:%S')
            })
        
        return JsonResponse({
            'code': CommonSuccessCode.success.value,
            'msg': '获取成功',
            'data': {
                'takeouts': takeouts_list,
                'total': paginator.count,
                'page': page,
                'size': size,
                'total_pages': paginator.num_pages
            }
        })
    except Exception as e:
        logger.error('[外卖列表] 错误: %s' % str(e))
        return JsonResponse({'code': CommonErrorCode.server_error.value, 'error': str(e)})


@csrf_exempt
@admin_required
def admin_get_pending_takeouts(request, admin=None):
    """
    获取待审核外卖列表
    GET /api/admin/takeouts/pending?admin_id=xxx
    """
    if request.method != 'GET':
        return JsonResponse({'code': CommonErrorCode.method_error.value, 'error': '请求方式错误'})
    
    try:
        takeouts = Takeout.objects.filter(state=TakeoutState.auditing.value).select_related('store').order_by('create_time')
        
        takeouts_list = []
        for takeout in takeouts:
            takeouts_list.append({
                'id': takeout.id,
                'takeout_name': takeout.takeout_name,
                'introduce': takeout.introduce,
                'price': takeout.price,
                'store': {
                    'id': takeout.store.id if takeout.store else '',
                    'name': takeout.store.store_name if takeout.store else 'N/A'
                },
                'create_time': takeout.create_time.strftime('%Y-%m-%d %H:%M:%S')
            })
        
        return JsonResponse({
            'code': CommonSuccessCode.success.value,
            'msg': '获取成功',
            'data': {
                'takeouts': takeouts_list,
                'total': len(takeouts_list)
            }
        })
    except Exception as e:
        logger.error('[待审核外卖] 错误: %s' % str(e))
        return JsonResponse({'code': CommonErrorCode.server_error.value, 'error': str(e)})


# ==================== 订单管理 ====================

@csrf_exempt
@admin_required
def admin_get_orders(request, admin=None):
    """
    获取订单列表
    GET /api/admin/orders?admin_id=xxx&page=1&size=20&state=xxx&user_id=xxx
    """
    if request.method != 'GET':
        return JsonResponse({'code': CommonErrorCode.method_error.value, 'error': '请求方式错误'})
    
    try:
        page = int(request.GET.get('page', 1))
        size = int(request.GET.get('size', 20))
        state_filter = request.GET.get('state', '')
        user_id = request.GET.get('user_id', '')
        
        # 构建查询
        query = Q()
        if state_filter != '':
            query &= Q(state=int(state_filter))
        if user_id:
            query &= Q(user_id=user_id)
        
        orders = Order.objects.filter(query).select_related('user', 'store', 'takeout').order_by('-create_time')
        
        # 分页
        paginator = Paginator(orders, size)
        page_obj = paginator.get_page(page)
        
        orders_list = []
        for order in page_obj:
            orders_list.append({
                'id': order.id,
                'order_id': order.order_id,
                'price': order.price,
                'count': order.count,
                'state': order.state,
                'state_name': '已完成' if order.state == OrderState.finished.value else '未完成',
                'payment_method': order.payment_method,
                'note': order.note,
                'user': {
                    'id': order.user.id if order.user else '',
                    'username': order.user.username if order.user else 'N/A',
                    'phone': order.user.phone if order.user else 'N/A'
                },
                'store': {
                    'id': order.store.id if order.store else '',
                    'name': order.store.store_name if order.store else 'N/A'
                },
                'takeout': {
                    'id': order.takeout.id if order.takeout else '',
                    'name': order.takeout.takeout_name if order.takeout else 'N/A'
                },
                'create_time': order.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                'finish_time': order.finish_time.strftime('%Y-%m-%d %H:%M:%S')
            })
        
        return JsonResponse({
            'code': CommonSuccessCode.success.value,
            'msg': '获取成功',
            'data': {
                'orders': orders_list,
                'total': paginator.count,
                'page': page,
                'size': size,
                'total_pages': paginator.num_pages
            }
        })
    except Exception as e:
        logger.error('[订单列表] 错误: %s' % str(e))
        return JsonResponse({'code': CommonErrorCode.server_error.value, 'error': str(e)})


# ==================== 统计分析 ====================

@csrf_exempt
@admin_required
def admin_get_statistics(request, admin=None):
    """
    获取统计数据
    GET /api/admin/statistics?admin_id=xxx&days=7
    """
    if request.method != 'GET':
        return JsonResponse({'code': CommonErrorCode.method_error.value, 'error': '请求方式错误'})
    
    try:
        days = int(request.GET.get('days', 7))
        
        # 时间范围
        end_date = datetime.now().date()
        start_date = end_date - timedelta(days=days-1)
        
        # 每日统计
        daily_stats = []
        for i in range(days):
            date = start_date + timedelta(days=i)
            date_start = datetime.combine(date, datetime.min.time())
            date_end = datetime.combine(date, datetime.max.time())
            
            daily_orders = Order.objects.filter(
                create_time__gte=date_start,
                create_time__lte=date_end
            )
            
            daily_stats.append({
                'date': date.strftime('%Y-%m-%d'),
                'orders': daily_orders.count(),
                'revenue': daily_orders.aggregate(total=Sum('price'))['total'] or 0,
                'new_users': User.objects.filter(id__contains=date.strftime('%Y%m%d')).count()
            })
        
        # 总体统计
        total_stats = {
            'users': User.objects.count(),
            'stores': Store.objects.count(),
            'takeouts': Takeout.objects.count(),
            'orders': Order.objects.count(),
            'revenue': Order.objects.aggregate(total=Sum('price'))['total'] or 0
        }
        
        return JsonResponse({
            'code': CommonSuccessCode.success.value,
            'msg': '获取成功',
            'data': {
                'daily_stats': daily_stats,
                'total_stats': total_stats
            }
        })
    except Exception as e:
        logger.error('[统计数据] 错误: %s' % str(e))
        return JsonResponse({'code': CommonErrorCode.server_error.value, 'error': str(e)})


# ==================== 辅助函数 ====================

def get_store_state_name(state):
    """获取商家状态名称"""
    state_map = {
        StoreState.auditing.value: '待审核',
        StoreState.audited.value: '已通过',
        StoreState.forbidden.value: '已封禁',
        StoreState.deleted.value: '已删除',
        StoreState.reject.value: '已拒绝'
    }
    return state_map.get(state, '未知')


def get_takeout_state_name(state):
    """获取外卖状态名称"""
    state_map = {
        TakeoutState.auditing.value: '待审核',
        TakeoutState.audited.value: '已通过',
        TakeoutState.forbidden.value: '已封禁',
        TakeoutState.deleted.value: '已删除',
        TakeoutState.reject.value: '已拒绝'
    }
    return state_map.get(state, '未知')


# ==================== 用户增删改功能 ====================

@csrf_exempt
@admin_required
def admin_delete_user(request, admin=None):
    """删除用户"""
    if request.method != 'POST':
        return JsonResponse({'code': CommonErrorCode.method_error.value, 'error': '请求方式错误'})
    
    try:
        data = json.loads(request.body)
        user_id = data.get('user_id')
        
        if not user_id:
            return JsonResponse({'code': CommonErrorCode.param_not_found.value, 'error': '缺少用户ID'})
        
        user = User.objects.get(id=user_id)
        
        # 不允许删除管理员
        if user.is_admin:
            return JsonResponse({'code': CommonErrorCode.operation_error.value, 'error': '不能删除管理员账号'})
        
        username = user.username
        user.delete()
        
        logger.info('[删除用户] 管理员:%s 删除用户:%s(%s)' % (admin.username, username, user_id))
        
        return JsonResponse({
            'code': CommonSuccessCode.success.value,
            'msg': '用户删除成功'
        })
    except User.DoesNotExist:
        return JsonResponse({'code': UserBackCode.user_not_found.value, 'error': '用户不存在'})
    except Exception as e:
        logger.error('[删除用户] 错误: %s' % str(e))
        return JsonResponse({'code': CommonErrorCode.server_error.value, 'error': str(e)})


@csrf_exempt
@admin_required
def admin_create_user(request, admin=None):
    """新增用户（管理员）"""
    if request.method != 'POST':
        return JsonResponse({'code': CommonErrorCode.method_error.value, 'error': '请求方式错误'})

    try:
        data = json.loads(request.body or '{}')
        username = data.get('username')
        phone = data.get('phone')
        password = data.get('password')
        is_admin = bool(data.get('is_admin', False))
        balance = data.get('balance', None)

        # 参数校验
        if not username or not phone or not password:
            return JsonResponse({'code': CommonErrorCode.param_not_found.value, 'error': '缺少必要参数（username/phone/password）'})

        import re
        if not re.fullmatch(r"\d{11}", str(phone)):
            return JsonResponse({'code': CommonErrorCode.param_error.value, 'error': '手机号格式不正确'})
        if len(str(password)) < 8 or len(str(password)) > 20:
            return JsonResponse({'code': CommonErrorCode.param_error.value, 'error': '密码长度需在8-20位之间'})

        # 重复校验（手机号唯一）
        if User.objects.filter(phone=phone).exists():
            return JsonResponse({'code': CommonErrorCode.operation_error.value, 'error': '该手机号已注册'})

        # 生成用户ID（包含日期前缀）
        import uuid
        new_id = 'USR' + datetime.now().strftime('%Y%m%d') + uuid.uuid4().hex[:8]

        # 创建用户
        user = User(
            id=new_id,
            username=username,
            phone=phone,
            password=password,
            is_admin=is_admin
        )
        if balance is not None:
            try:
                user.money = float(balance)
            except Exception:
                # 如果余额解析失败，忽略并使用默认值
                pass
        user.save()

        logger.info('[新增用户] 管理员:%s 新增用户:%s(%s) 管理员:%s' % (
            admin.username, username, new_id, '是' if is_admin else '否'
        ))

        return JsonResponse({
            'code': CommonSuccessCode.success.value,
            'msg': '用户创建成功',
            'data': {
                'id': user.id,
                'username': user.username,
                'phone': user.phone,
                'is_admin': user.is_admin,
                'balance': user.money
            }
        })
    except Exception as e:
        logger.error('[新增用户] 错误: %s' % str(e))
        return JsonResponse({'code': CommonErrorCode.server_error.value, 'error': str(e)})


@csrf_exempt
@admin_required
def admin_update_user(request, admin=None):
    """编辑用户信息"""
    if request.method != 'POST':
        return JsonResponse({'code': CommonErrorCode.method_error.value, 'error': '请求方式错误'})
    
    try:
        data = json.loads(request.body)
        user_id = data.get('user_id')
        username = data.get('username')
        phone = data.get('phone')
        
        if not user_id:
            return JsonResponse({'code': CommonErrorCode.param_not_found.value, 'error': '缺少用户ID'})
        
        user = User.objects.get(id=user_id)
        
        if username:
            user.username = username
        if phone:
            user.phone = phone
        
        user.save()
        
        logger.info('[编辑用户] 管理员:%s 编辑用户:%s' % (admin.username, user_id))
        
        return JsonResponse({
            'code': CommonSuccessCode.success.value,
            'msg': '用户信息更新成功',
            'data': {
                'id': user.id,
                'username': user.username,
                'phone': user.phone
            }
        })
    except User.DoesNotExist:
        return JsonResponse({'code': UserBackCode.user_not_found.value, 'error': '用户不存在'})
    except Exception as e:
        logger.error('[编辑用户] 错误: %s' % str(e))
        return JsonResponse({'code': CommonErrorCode.server_error.value, 'error': str(e)})


# ==================== 商家删除功能 ====================

@csrf_exempt
@admin_required
def admin_delete_store(request, admin=None):
    """删除商家"""
    if request.method != 'POST':
        return JsonResponse({'code': CommonErrorCode.method_error.value, 'error': '请求方式错误'})
    
    try:
        data = json.loads(request.body)
        store_id = data.get('store_id')
        
        if not store_id:
            return JsonResponse({'code': CommonErrorCode.param_not_found.value, 'error': '缺少商家ID'})
        
        store = Store.objects.get(id=store_id)
        store_name = store.store_name
        store.delete()
        
        logger.info('[删除商家] 管理员:%s 删除商家:%s(%s)' % (admin.username, store_name, store_id))
        
        return JsonResponse({
            'code': CommonSuccessCode.success.value,
            'msg': '商家删除成功'
        })
    except Store.DoesNotExist:
        return JsonResponse({'code': CommonErrorCode.data_not_found.value, 'error': '商家不存在'})
    except Exception as e:
        logger.error('[删除商家] 错误: %s' % str(e))
        return JsonResponse({'code': CommonErrorCode.server_error.value, 'error': str(e)})


# ==================== 外卖删除功能 ====================

@csrf_exempt
@admin_required
def admin_delete_takeout(request, admin=None):
    """删除外卖"""
    if request.method != 'POST':
        return JsonResponse({'code': CommonErrorCode.method_error.value, 'error': '请求方式错误'})
    
    try:
        data = json.loads(request.body)
        takeout_id = data.get('takeout_id')
        
        if not takeout_id:
            return JsonResponse({'code': CommonErrorCode.param_not_found.value, 'error': '缺少外卖ID'})
        
        takeout = Takeout.objects.get(id=takeout_id)
        takeout_name = takeout.takeout_name
        takeout.delete()
        
        logger.info('[删除外卖] 管理员:%s 删除外卖:%s(%s)' % (admin.username, takeout_name, takeout_id))
        
        return JsonResponse({
            'code': CommonSuccessCode.success.value,
            'msg': '外卖删除成功'
        })
    except Takeout.DoesNotExist:
        return JsonResponse({'code': CommonErrorCode.data_not_found.value, 'error': '外卖不存在'})
    except Exception as e:
        logger.error('[删除外卖] 错误: %s' % str(e))
        return JsonResponse({'code': CommonErrorCode.server_error.value, 'error': str(e)})


# ==================== 订单管理功能 ====================

@csrf_exempt
@admin_required
def admin_delete_order(request, admin=None):
    """删除订单"""
    if request.method != 'POST':
        return JsonResponse({'code': CommonErrorCode.method_error.value, 'error': '请求方式错误'})
    
    try:
        data = json.loads(request.body)
        order_id = data.get('order_id')
        
        if not order_id:
            return JsonResponse({'code': CommonErrorCode.param_not_found.value, 'error': '缺少订单ID'})
        
        order = Order.objects.get(id=order_id)
        order.delete()
        
        logger.info('[删除订单] 管理员:%s 删除订单:%s' % (admin.username, order_id))
        
        return JsonResponse({
            'code': CommonSuccessCode.success.value,
            'msg': '订单删除成功'
        })
    except Order.DoesNotExist:
        return JsonResponse({'code': CommonErrorCode.data_not_found.value, 'error': '订单不存在'})
    except Exception as e:
        logger.error('[删除订单] 错误: %s' % str(e))
        return JsonResponse({'code': CommonErrorCode.server_error.value, 'error': str(e)})


@csrf_exempt
@admin_required
def admin_update_order_state(request, admin=None):
    """修改订单状态"""
    if request.method != 'POST':
        return JsonResponse({'code': CommonErrorCode.method_error.value, 'error': '请求方式错误'})
    
    try:
        data = json.loads(request.body)
        order_id = data.get('order_id')
        new_state = data.get('state')
        
        if not order_id or new_state is None:
            return JsonResponse({'code': CommonErrorCode.param_not_found.value, 'error': '缺少必要参数'})
        
        order = Order.objects.get(id=order_id)
        old_state = order.state
        order.state = int(new_state)
        order.save()
        
        logger.info('[修改订单状态] 管理员:%s 订单:%s 状态:%s->%s' % (admin.username, order_id, old_state, new_state))
        
        return JsonResponse({
            'code': CommonSuccessCode.success.value,
            'msg': '订单状态更新成功'
        })
    except Order.DoesNotExist:
        return JsonResponse({'code': CommonErrorCode.data_not_found.value, 'error': '订单不存在'})
    except Exception as e:
        logger.error('[修改订单状态] 错误: %s' % str(e))
        return JsonResponse({'code': CommonErrorCode.server_error.value, 'error': str(e)})

